#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->treeWidget->setHeaderLabel("动物");

    //添加三个顶层节点
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0,"猫");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0,"狗");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item3->setText(0,"兔");
    ui->treeWidget->addTopLevelItem(item3);

    //添加子节点
    QTreeWidgetItem* item4 = new QTreeWidgetItem();
    item4->setText(0,"暹罗");
    item1->addChild(item4);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    const QString& str = ui->lineEdit->text();
    if(str.isEmpty())
        return;
    QTreeWidgetItem* newItem = new QTreeWidgetItem();
    newItem->setText(0,str);
    ui->treeWidget->addTopLevelItem(newItem);
}

void Widget::on_pushButton_2_clicked()
{
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if(currentItem==nullptr)
    {
        return;
    }

    const QString& str = ui->lineEdit->text();
    if(str.isEmpty())
        return;
    QTreeWidgetItem* newItem = new QTreeWidgetItem();
    newItem->setText(0,str);
    currentItem->addChild(newItem);

}

void Widget::on_pushButton_3_clicked()
{
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if(currentItem==nullptr)
        return;

    QTreeWidgetItem* father = currentItem->parent();
    if(father==nullptr)
    {
        //说明currentItem是顶层节点

        //因为只能通过下标删除顶层节点，所以需要先得到currentItem的index
        int index = ui->treeWidget->indexOfTopLevelItem(currentItem);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        //说明currentItem是普通节点
        father->removeChild(currentItem);
    }
}
